import 'dart:async';

import 'package:camera/camera.dart';
import 'package:get/get.dart';
import 'package:largefriends/config/lf_route.dart';
import 'package:largefriends/entity/entities/lf_gesture_entity.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../../res/strings/lf_strings.dart';
import '../../../utils/lf_dialog_utils.dart';
import '../../../widgets/dialog_action_tip.dart';
import '../lf_verify_camera_confirm/lf_verify_camera_confirm_logic.dart';

toVerifyCamera({required LfGestureEntity gesture, bool needOff = false}) async {
  var cameraStatus = await Permission.camera.request();
  if (cameraStatus == PermissionStatus.granted ||
      cameraStatus == PermissionStatus.provisional) {
    var audioStatus = await Permission.microphone.request();
    if (audioStatus == PermissionStatus.granted ||
        audioStatus == PermissionStatus.provisional) {
      if (needOff) {
        Get.offAndToNamed(LFRoute.pathVerifyCamera,
            arguments: {'gesture': gesture});
      } else {
        Get.toNamed(LFRoute.pathVerifyCamera, arguments: {'gesture': gesture});
      }
    } else {
      showActionTips(
          tips: strRecordMicAccessTip.tr,
          actionButtonTip: strContinue.tr,
          action: () {
            openAppSettings();
          });
    }
  } else {
    showActionTips(
        tips: strRecordMicrophoneTip.tr,
        actionButtonTip: strContinue.tr,
        action: () {
          openAppSettings();
        });
  }
}

class LfVerifyCameraLogic extends GetxController {
  late LfGestureEntity gestureEntity;

  CameraController? cameraController;
  int loadState = 0;

  String errorTips = "";

  ///0: 初始化中, 1: 初始化成功, 2:初始化失败, 没有相机?

  @override
  void onInit() async {
    gestureEntity = Get.arguments['gesture'];
    super.onInit();
    initCamera();
  }

  void initCamera() async {
    if (loadState == 2) {
      loadState = 0;
      update();
    }
    var cameras = await availableCameras();

    if (cameras.isEmpty) {
      loadState = 2;
      update();
      return;
    }
    var camera = cameras.firstWhereOrNull(
        (element) => element.lensDirection == CameraLensDirection.front);
    if (camera == null) {
      ///没找到前置摄像头
      loadState = 2;
      update();
      return;
    }
    cameraController = CameraController(
      camera,
      ResolutionPreset.max,
    );
    errorTips = "";
    cameraController?.initialize().then((_) {
      loadState = 1;
      update();
    }).catchError((Object e) {
      loadState = 2;
      if (e is CameraException) {
        ///TODO 权限处理
        switch (e.code) {
          case 'CameraAccessDenied':
            errorTips = "CameraAccessDenied";
            break;
          case 'AudioAccessDenied':
            errorTips = "AudioAccessDenied";
            break;
          default:
            errorTips = "Other";
            break;
        }
      } else {
        errorTips = "Other";
      }
      update();
    });
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    cameraController?.dispose();
    super.onClose();
  }

  RxBool isRecording = false.obs;
  Timer? _timer;
  RxInt duration = 0.obs;

  void startRecord() async {
    if (isRecording.isTrue) {
      return;
    }
    isRecording.value = true;
    await cameraController?.startVideoRecording().then((value) {
      _timer = Timer.periodic(const Duration(milliseconds: 50), (t) {
        duration.value = duration.value + 50;
        if (duration.value == 8000) {
          endRecord();
        }
      });
    }).onError((error, stackTrace) {
      isRecording.value = false;
    });
  }

  void endRecord() async {
    _timer?.cancel();
    isRecording.value = false;
    var videoFile = await cameraController?.stopVideoRecording();
    var videoDuration = duration.value;
    duration.value = 0;
    if (videoDuration < 3000 || videoFile == null) {
      showSnackBar(strKeepVideoDurationTip.tr);
      return;
    } else {
      toVerifyCameraConfirm(entity: gestureEntity, video: videoFile!);
    }
  }
}
